/*
* Copyright 2011 Joshua Carbonneau
*
* This file is part of Texture Chaos.
*
* Texture Chaos is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Texture Chaos is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Texture Chaos.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <png.h>

#include "include/chaos.h"
#include "include/simplepng.h"
#include "include/tilemap.h"

// Default configfile names
#define TEXMAPNAME "data/texmap.txt"

/******************************************
* Parse command line args, read in the    *
* input file(s), process them, and output *
* the modified files(s)                   *
*******************************************/
int main(int argc, char** argv)
{
    parseArgs(argc, argv);

    debug(0, "Input file: %s\nOutput file: %s\nTilemap File: %s\n", 
          infileName, outfileName, texmapName);
    debug(0, "Debug level: %d\n\n", debugLevel);

    struct SimplePng* sp = newSimplePng(infileName);
    if(sp == 0)
    {
        debug(0, "Failed to create SimplePng with file %s!\n", infileName);
        freeStrings();
        exit(0);
    }
    struct TileMap* tm = newTileMap(texmapName);
    if(tm == 0)
    {
        debug(0, "Failed to create TileMap with file %s!\n", texmapName);
        freeStrings();
        exit(0);
    }

    int rtlya, rtlxa, rbrya, rbrxa;
    int rtlyb, rtlxb, rbryb, rbrxb;
    int i;

    // Switch tiles around if the -s option was given on the command line
    if(numSwitches > 0)
    {
        // Get two random tiles, then switch them
        debug(0, "Doing %d switches...\n", numSwitches);
        for(i=0; i < numSwitches; i++)
        {
            getRandomTileCoord(tm, &rtlya, &rtlxa, &rbrya, &rbrxa);
            getRandomTileCoord(tm, &rtlyb, &rtlxb, &rbryb, &rbrxb);
            debug(2, "Switching (%d, %d) and (%d, %d)\n", rtlya, rtlxa,
                  rtlyb, rtlxb);
            switchBlocks(sp, rtlya, rtlxa, rbrya, rbrxa, rtlyb, rtlxb);
        }
        debug(0, "Done!\n\n");
    }

    // Colorshift some tiles if the -h option was given on the command line
    if(numShifts > 0)
    {
        debug(0, "Color shifting %d tiles...\n", numShifts);
        for(i=0; i < numShifts; i++)
        {
            getRandomTileCoord(tm, &rtlya, &rtlxa, &rbrya, &rbrxa);
            debug(2, "Color shifting (%d, %d)\n", rtlya, rtlxa);
            shiftColors(sp, rtlya, rtlxa, rbrya, rbrxa);
        }
        debug(0, "Done!\n\n");
    }

    // Randomize some tiles if the -r option was given on the command line
    if(numRandoms > 0)
    {
        // Get a random tile, then randomize its color
        debug(0, "Doing %d color randomizations...\n", numRandoms);
        for(i=0; i < numRandoms; i++)
        {
            getRandomTileCoord(tm, &rtlya, &rtlxa, &rbrya, &rbrxa);
            debug(2, "Randomizing (%d, %d)\n", rtlya, rtlxa);
            randomizeColor(sp, rtlya, rtlxa, rbrya, rbrxa);
        }
        debug(0, "Done!\n\n");
    }

    // Average some tiles if the -r option was given on the command line
    if(numAverages > 0)
    {
        // Get a random tile, then average its color
        debug(0, "Doing %d color averages...\n", numAverages);
        for(i=0; i < numAverages; i++)
        {
            getRandomTileCoord(tm, &rtlya, &rtlxa, &rbrya, &rbrxa);
            debug(2, "Averaging (%d, %d)\n", rtlya, rtlxa);
            averageColor(sp, rtlya, rtlxa, rbrya, rbrxa);
        }
        debug(0, "Done!\n\n");
    }

    debug(0, "Writing output file %s...\n", outfileName);
    writePngFile(sp, outfileName);
    debug(0, "Done!\n\n");

    debug(0, "Cleaning up...\n");
    destroySimplePng(sp);
    destroyTileMap(tm);
    freeStrings();
    debug(0, "Done!\n\n");

    return 0;
}

/*******************************************
* Convert a string into an integer         *
* a: The string to convert                 *
* returns: The integer representation of a *
********************************************/
int str2int(char* a)
{
    // Start at the end of the string and work backwards
    int i = strlen(a) - 1;
    int e = 1;
    int n = 0;
    while(i >= 0)
    {
        n = n + ((a[i] - '0') * e);
        e = e * 10;
        i--;
    }
    return n;
}

/***************************************
* Parse the command line arguments and *
* set variables accordingly            *
* argc: Number of arguments            *
* argv: Array of argument strings      *
****************************************/
void parseArgs(int argc, char** argv)
{
    // Set executable name and default integer option values
    exName = (char*)malloc(sizeof(char) * (strlen(argv[0]) + 1));
    strcpy(exName, argv[0]);
    debugLevel = 0;
    numSwitches = 0;

    // Parse each argument
    while(argc > 2 && argv[1][0] == '-')
    {
        switch(argv[1][1])
        {
            case 's':
                numSwitches = str2int(argv[2]);
                argv++;
                argc--;
                break;
            case 'd':
                debugLevel = str2int(argv[2]);
                argv++;
                argc--;
                break;
            case 'h':
                numShifts = str2int(argv[2]);
                argv++;
                argc--;
                break;
            case 'r':
                numRandoms = str2int(argv[2]);
                argv++;
                argc--;
                break;
            case 'a':
                numAverages = str2int(argv[2]);
                argv++;
                argc--;
                break;
            case 'i':
                infileName = (char*)malloc(sizeof(char) * (strlen(argv[2]) + 1));
                strcpy(infileName, argv[2]);
                argv++;
                argc--;
                break;
            case 'o':
                outfileName = (char*)malloc(sizeof(char) * (strlen(argv[2]) + 1));
                strcpy(outfileName, argv[2]);
                argv++;
                argc--;
                break;
            case 't':
                texmapName = (char*)malloc(sizeof(char) * (strlen(argv[2]) + 1));
                strcpy(texmapName, argv[2]);
                argv++;
                argc--;
                break;
            default:
                debug(0, "unknown option '%c'", argv[1][1]);
                exit(1);
        }
        argv++;
        argc--;
    }
    // If no tilemap file given, use default
    if(texmapName == 0)
    {
        texmapName = (char*)malloc(sizeof(char) * (strlen(TEXMAPNAME) + 1));
        strcpy(texmapName, TEXMAPNAME);
        debug(1, "No tilemap file given, using default: %s\n", texmapName);
    }
    // Check for input and output files
    if(outfileName == 0 || infileName == 0)
    {
        printUsage();
        freeStrings();
        exit(0);
    }
    // Make sure debugLevel is not less than -1
    if(debugLevel < -1)
        debugLevel = -1;
}

/*******************************************
* Print a message to stdout (if debugLevel * 
* is greater or equal to level).           *
* level: The level of the debug message    *
* format: Format string                    *
********************************************/
void debug(int level, char *format, ...)
{
    // Send the format string and args to printf
    if (level <= debugLevel) 
    {
        va_list ap;
        va_start(ap, format);
        vfprintf(stdout, format, ap);
        va_end(ap);
        fflush(stdout);
    }
}

/********************************************
* Free strings for filenames and executable *
*********************************************/
void freeStrings()
{
    if(infileName != 0) free(infileName);
    if(outfileName != 0) free(outfileName);
    if(texmapName != 0) free(texmapName);
    if(exName != 0) free(exName);
}

/*******************************************
* Print the usage of the program to stdout *
********************************************/
void printUsage()
{
    printf("usage: %s -i <inputfile> -o <outputfile> [options]\n", exName);
    printf("\toptions:\n");
    printf("\t-d <debug-level> Set the level of debug messages (0-3)\n");
    printf("\t-t <texmap> Specify the config file for the tilemap\n");
    printf("\t-s <numberOfSwaps> Specify the number of tileswaps to perform on the image\n");
    printf("\t-h <numberOfColorshifts> Specify the number of random colorshifts to preform on the image\n");
    printf("\t-a <numberOfAverages> Specify the number of random tile color averages to preform on the image\n");
    printf("\t-r <numberOfRandomizations> Specify the number of random tile color randomizations to preform on the image\n");
}
